package utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;

import primitive.SortPair;

public class SortStack {
	
	public enum mode_t { ASC, DESC };
	
	private int size = 5;
	private List<SortPair> stack;
	private mode_t mode;
	
	public SortStack(int size) {
		this.size = size;
		
		stack = new ArrayList<SortPair>();
		for (int i = 0; i < size; ++i) {
			stack.add(new SortPair());
			stack.get(i).first = 9999999.9;
		}
		
		mode = mode_t.ASC;
	}
	
	public void setMode(mode_t m) {
		mode = m;
		
		// If we gonna use this stack for SimilarityMeasures, we ought to collect the biggest values
		//		if similarity between two objects are bigger then its better
		if (mode == mode_t.DESC) {				// ...	
			for (int i = 0; i < size; ++i) {
				stack.get(i).first = 0.0;
			}
		}
	}
	
	public void append(SortPair pair) {
		//
		if (mode == mode_t.ASC) {
			for (int i = 0; i < size; ++i) {
				if (pair.first < stack.get(i).first) {
					// Replace
					stack.remove(size - 1);
					stack.add(i, pair);
					break;
				}
			}
		} else if (mode == mode_t.DESC) {
			for (int i = 0; i < size; ++i) {
				if (pair.first > stack.get(i).first) {
					// Replace
					stack.remove(size - 1);
					stack.add(i, pair);
					break;
				}
			}
		}
	}
	
	public void clear() {
		if (mode == mode_t.ASC) {
			for (int i = 0; i < size; ++i) {
				stack.get(i).first = 9999999.9;
				stack.get(i).second = null;
			}
		} else if (mode == mode_t.DESC) {
			for (int i = 0; i < size; ++i) {
				stack.get(i).first = 0.0;
				stack.get(i).second = null;
			}
		}
	}
	
	public void clear_2() {
		for (int i = 0; i < size; ++i) {
			if (mode == mode_t.ASC) {
				stack.get(i).first = 9999999.9;
			} else if (mode == mode_t.DESC) {
				stack.get(i).first = 0.0;
			}
			stack.get(i).second = null;
		}
	}
	
	public String get_most_popular() {
		String most_category = "";
		
		HashMap<String, Integer> most = new HashMap<>();
		
		//System.out.println(stack);
		
		for (int i = 0; i < stack.size(); ++i) {
			if (most.containsKey(stack.get(i).second)) {
				int c = most.get(stack.get(i).second) + 1;
				most.put(stack.get(i).second, c);
			} else {
				most.put(stack.get(i).second, 1);
			}
		}
		
		int max = -1;
		String key;
		Iterator<String> it = most.keySet().iterator();
		
		while (it.hasNext()) {
			key = it.next();
			
			if (most.get(key) > max) {
				max = most.get(key);
				most_category = key;
			}
		}
		
		return most_category;
	}
	
	public List<SortPair> get_results() {
		return stack;
	}
}